import widgetService from '@/api/widgetService'
import BtnEventHelpFn from './btnEventHelpUtil'

export function createProcessor (owner) {
  return new Processor(owner)
}

function Processor (owner) {
  this.owner = owner
  this.btnEventHelpUtil = new BtnEventHelpFn(owner)

  //

  function enterDetail (routerName, params, query) {
    if (params.hideHeader) {
      const {href} = owner.$router.resolve({
        name: routerName,
        params: params,
        query
      })
      window.open(href, '_blank')
    } else {
      owner.$router.push({
        name: routerName,
        params: params,
        query : query
      })
    }
  }

  function getRouterParam (routerParam, project) {
    const arr = routerParam.split('/:')
    const param = {}
    owner.rowData = project || owner.rowData
    if (arr.length > 1) {
      arr.forEach((item, index) => {
        if (index > 0) {
          param[item] = owner.rowData[item] || owner.rowData[item.toUpperCase()] || 0
        }
      })
    }
    return param
  }

  this.refresh = btn => {
    owner.filter.filterText = ''
    owner.loadData()
  }

  this.search = btn => {
    owner.filter.pageIndex = 1
    owner.loadData()
  }

  this.click = btn => {
    widgetService.getCustomWidgetById(btn.usedWidgetId).then(d => {
      const param = getRouterParam(d.routerParam)
      if (d.desc === 'edit') {
        param.isEdit = true // 表单可编辑
      }
      if (owner.rowData.taskId) {
        enterDetail(d.routerName, param, { taskId: owner.rowData.taskId })
      } else {
        enterDetail(d.routerName, param)
      }
    })
  }

  this.dblclick = (btn, params = {}) => {
    widgetService.getCustomWidgetById(btn.usedWidgetId).then(d => {
      const param = getRouterParam(d.routerParam)
      if (d.desc === 'edit') {
        param.isEdit = true // 表单可编辑
      }
      if (owner.rowData.PROCESSSTATE && owner.rowData.PROCESSSTATE === '补正') {
        param.isEdit = false
      }
      // 上报中表单不可编辑
      if (owner.rowData.F_STATUS && (owner.rowData.F_STATUS & 2) === 2) {
        params.readonly = true
      }
      if (d.desc === 'readOnly') {
        param.isEdit = false // 表单可编辑
      }
      if (owner.rowData.taskId && !params.readonly) {
        enterDetail(d.routerName, param, {
          taskId: owner.rowData.taskId,
          correctId: owner.rowData.CORRECTID,
          projectId: owner.rowData.projectId,
          activityName: owner.rowData.activityName,
          title: owner.rowData.xmmc || owner.rowData.XMMC
        })
      } else {
        enterDetail(d.routerName, param, {
          taskId: owner.rowData.taskId || owner.rowData.TASKID,
          projectId: owner.rowData.projectId || owner.rowData.PID,
          readonly: params.readonly === true,
          title: owner.rowData.xmmc || owner.rowData.XMMC
        })
      }
    })
  }
}

export default {
  createProcessor
}
